package com.flower.service.impl;

import com.flower.domain.dto.admin.OrderDto;
import com.flower.domain.entity.FlowerEncyclopedia;
import com.flower.domain.entity.Order;
import com.flower.domain.entity.OrderItem;
import com.flower.domain.entity.Product;
import com.flower.domain.vo.admin.area.FlowerEncyclopediaArea;
import com.flower.domain.vo.admin.area.OrderArea;
import com.flower.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class AreaAnalysisServiceImpl implements AreaAnalysisService {

    private final FlowerEncyclopediaService flowerEncyclopediaService;
    private final OrderService orderService;
    private final OrderItemService orderItemService;
    private final ProductService productService;

    @Override
    public List<FlowerEncyclopediaArea> getSpecieWithProvince() {
        // 获取花卉百科中的全部数据
        List<FlowerEncyclopedia> flowerEncyclopediaList = flowerEncyclopediaService.lambdaQuery().list();

        // 存储信息
        List<FlowerEncyclopediaArea> flowerEncyclopediaAreas = new ArrayList<>();
        Map<String, List<Integer>> map = new HashMap<>();

        // 获取花卉百科中全部省份的对应的花的品种id
        for (FlowerEncyclopedia flowerEncyclopedia : flowerEncyclopediaList) {
            String provinces = flowerEncyclopedia.getRightPlace();
            if (provinces == null) continue;

            // 将provinces用 "、" 分开
            String[] provinceArray = provinces.split("、");
            for (String province : provinceArray) {
                if (province.isEmpty()) continue;  // 新增空字符串过滤

                // 使用 computeIfAbsent 优化存在性判断
                map.computeIfAbsent(province, k -> new ArrayList<>())
                        .add(Math.toIntExact(flowerEncyclopedia.getId()));
            }
        }

        // 构建返回结果
        for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
            FlowerEncyclopediaArea flowerEncyclopediaArea = new FlowerEncyclopediaArea();
            flowerEncyclopediaArea.setProvinceName(entry.getKey());
            flowerEncyclopediaArea.setFlowerName(entry.getValue().stream()
                    .map(id -> flowerEncyclopediaService.getById(id).getName())
                    .collect(Collectors.toList()));
            flowerEncyclopediaArea.setCount((long) entry.getValue().size());
            flowerEncyclopediaAreas.add(flowerEncyclopediaArea);
        }
        return flowerEncyclopediaAreas;
    }


    @Override
    public List<OrderArea> getSaleWithProvince() {
        // 获取订单的全部数据（用户订单且状态为已完成）
        List<Order> OrderList = orderService.lambdaQuery()
                .eq(Order::getShopId, 0) // shopId=0 表示用户订单（非商家订单）
                .eq(Order::getStatus, 3) // 订单状态3表示已完成
                .list();

        // 存储省份和对应订单信息的映射关系（Key:省份名称，Value:该省对应的商品DTO列表）
        Map<String, List<OrderDto>> provinceOrderMap = new HashMap<>();

        // 遍历所有订单
        for (Order order : OrderList) {
            // 获取当前订单的明细项
            List<OrderItem> orderItems = orderItemService.lambdaQuery()
                    .eq(OrderItem::getOrderId, order.getOrderId())
                    .list();

            // 处理每个订单项中的商品
            for (OrderItem orderItem : orderItems) {
                // 根据商品ID查询商品详细信息
                List<Product> products = productService.lambdaQuery()
                        .eq(Product::getProductId, orderItem.getProductId())
                        .list();

                // 遍历商品信息（通常每个订单项对应一个商品）
                for (Product product : products) {
                    String region = product.getRegion();
                    if (region == null) continue; // 跳过无地域信息的商品

                    // 分割地域信息（格式示例："浙江省 杭州市"），取第一个作为省份
                    String[] regionParts = region.split(" ");
                    String province = regionParts[0]; // 省份/直辖市名称

                    // 构建省份-商品映射关系
                    if (provinceOrderMap.containsKey(province)) {
                        // 已存在该省份记录：创建新DTO并添加到列表
                        OrderDto orderDto = new OrderDto();
                        orderDto.setProductProvince(province);
                        orderDto.setProductId(product.getProductId());
                        provinceOrderMap.get(province).add(orderDto);
                    } else {
                        // 新省份记录：初始化列表并添加首条数据
                        List<OrderDto> newProvinceList = new ArrayList<>();
                        OrderDto orderDto = new OrderDto();
                        orderDto.setProductProvince(province);
                        orderDto.setProductId(product.getProductId());
                        newProvinceList.add(orderDto);
                        provinceOrderMap.put(province, newProvinceList);
                    }
                }
            }
        }

        // 构建最终返回结果列表
        List<OrderArea> resultList = new ArrayList<>();
        for (Map.Entry<String, List<OrderDto>> entry : provinceOrderMap.entrySet()) {
            OrderArea orderArea = new OrderArea();
            String provinceName = entry.getKey();

            // 设置基础省份信息
            orderArea.setProvinceName(provinceName);

            // 统计各商品出现次数（Key:商品ID，Value:出现次数）
            Map<Integer, Integer> productFrequency = new HashMap<>();
            for (OrderDto dto : entry.getValue()) {
                // 确保当前DTO属于当前省份（冗余校验）
                if (dto.getProductProvince().equals(provinceName)) {
                    productFrequency.merge(dto.getProductId(), 1, Integer::sum);
                }
            }

            // 确定销量最佳商品（出现次数最多的商品ID）
            Optional<Map.Entry<Integer, Integer>> bestProduct = productFrequency.entrySet()
                    .stream()
                    .max(Map.Entry.comparingByValue());

            // 设置最佳商品信息
            if (bestProduct.isPresent()) {
                Integer productId = bestProduct.get().getKey();
                // 查询商品服务获取商品名称
                orderArea.setBestFlower(productService.getById(productId).getProductName());
                orderArea.setBestFlowerCount(bestProduct.get().getValue());
            } else {
                orderArea.setBestFlower("暂时没有");
                orderArea.setBestFlowerCount(0);
            }

            // 设置省份维度统计信息
            orderArea.setFlowerCount(productFrequency.size()); // 商品种类数
            orderArea.setFlowerName(
                    productFrequency.keySet().stream()
                            .map(productId -> productService.getById(productId).getProductName())
                            .collect(Collectors.toList())
            );

            resultList.add(orderArea);
        }

        return resultList;
    }

}
